#!/bin/bash
# 全自动部署脚本 - 包含目录创建和权限管理
# 测试环境：Ubuntu 20.04+/CentOS 7+


WEB_ROOT="/data/www/php"       
LOG_DIR="/data/logs"             
SOURCE_URL="https://gitee.com/zxc72/repository/raw/master/app.zip"  
CONFIG_FILE="/data/www/php/config.php" 


generate_credentials() {
    DB_NAME="db_$(openssl rand -hex 4 | tr '[:lower:]' '[:upper:]')"
    DB_USER="user_$(openssl rand -hex 3 | tr -cd 'a-zA-Z0-9')"
    DB_PASS=$(openssl rand -base64 16 | tr -dc 'A-HJ-NP-Za-km-z1-9!#%' | head -c 18)
    
    
    [[ ${#DB_NAME} -ge 8 && ${#DB_USER} -ge 8 && ${#DB_PASS} -ge 12 ]] || {
        echo "❌ 凭证生成失败" >&2
        exit 1
    }
}


create_directories() {
    echo "📂 创建目录结构..."
    
    
    if [ ! -d "$WEB_ROOT" ]; then
        mkdir -p "$WEB_ROOT" || {
            echo "❌ 无法创建网站目录：$WEB_ROOT" >&2
            exit 1
        }
        echo "✅ 已创建网站目录：$WEB_ROOT"
    fi
    
    
    if [ ! -d "$LOG_DIR" ]; then
        mkdir -p "$LOG_DIR" || {
            echo "❌ 无法创建日志目录：$LOG_DIR" >&2
            exit 1
        }
        echo "✅ 已创建日志目录：$LOG_DIR"
    fi
    
    
    chown -R www-data:www-data "$WEB_ROOT" || exit 1
    chown -R www-data:www-data "$LOG_DIR" || exit 1
    find "$WEB_ROOT" -type d -exec chmod 750 {} \;
    find "$LOG_DIR" -type d -exec chmod 755 {} \;
}


install_dependencies() {
    echo "🔧 安装系统依赖..."
    
    
    if command -v apt &> /dev/null; then
        # Ubuntu/Debian
        export DEBIAN_FRONTEND=noninteractive
        apt-get update -qq
        apt-get install -y -qq \
            nginx \
            php-fpm \
            php-mysql \
            mysql-server \
            unzip \
            wget \
            || exit 1
            
    elif command -v yum &> /dev/null; then
        # CentOS/RHEL
        yum install -y -q \
            epel-release \
            yum-utils \
            || exit 1
            
        yum install -y -q \
            nginx \
            php \
            php-fpm \
            php-mysqlnd \
            mariadb-server \
            unzip \
            wget \
            || exit 1
            
        systemctl start mariadb
        systemctl enable mariadb
    else
        echo "❌ 不支持的Linux发行版" >&2
        exit 1
    fi
}


setup_database() {
    echo "🗃️ 初始化数据库..."
    
    
    mysql -e "DELETE FROM mysql.user WHERE User='';"
    mysql -e "DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');"
    mysql -e "FLUSH PRIVILEGES;"
    
    
    mysql -e "CREATE DATABASE IF NOT EXISTS \`$DB_NAME\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" || exit 1
    mysql -e "CREATE USER '$DB_USER'@'localhost' IDENTIFIED BY '$DB_PASS';" || exit 1
    mysql -e "GRANT ALL PRIVILEGES ON \`$DB_NAME\`.* TO '$DB_USER'@'localhost';" || exit 1
    mysql -e "FLUSH PRIVILEGES;" || exit 1
}


deploy_application() {
    echo "🚀 部署应用程序..."
    
    TEMP_DIR=$(mktemp -d)
    trap 'rm -rf "$TEMP_DIR"' EXIT
    
    
    if ! wget -q --timeout=30 -O "$TEMP_DIR/source.zip" "$SOURCE_URL"; then
        echo "❌ 源码下载失败" >&2
        exit 1
    fi
    
    
    if ! unzip -q "$TEMP_DIR/source.zip" -d "$TEMP_DIR"; then
        echo "❌ 文件解压失败" >&2
        exit 1
    fi
    
    
    APP_DIR=$(find "$TEMP_DIR" -maxdepth 1 -type d ! -path "$TEMP_DIR" -print -quit)
    [ -z "$APP_DIR" ] && {
        echo "❌ 无效的源码包结构" >&2
        exit 1
    }
    
    
    CONFIG_PATH="$APP_DIR/$CONFIG_FILE"
    [ ! -f "$CONFIG_PATH" ] && {
        echo "❌ 找不到配置文件：$CONFIG_FILE" >&2
        exit 1
    }
    
    sed -i.bak \
        -e "s/{{DB_NAME}}/$DB_NAME/g" \
        -e "s/{{DB_USER}}/$DB_USER/g" \
        -e "s/{{DB_PASSWORD}}/$DB_PASS/g" \
        "$CONFIG_PATH" || exit 1
    
    
    rsync -a --delete "$APP_DIR/" "$WEB_ROOT/" || exit 1
}


configure_webserver() {
    echo "🌐 配置Web服务器..."
    
    
    cat > /etc/nginx/conf.d/myapp.conf <<EOF
server {
    listen 80;
    listen [::]:80;
    server_name _;
    
    root $WEB_ROOT;
    index index.php index.html;
    
    access_log $LOG_DIR/access.log;
    error_log $LOG_DIR/error.log;
    
    location / {
        try_files \$uri \$uri/ /index.php?\$args;
    }
    
    location ~ \.php\$ {
        include fastcgi_params;
        fastcgi_pass unix:/run/php/php-fpm.sock;
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
        fastcgi_param PHP_VALUE "error_log=$LOG_DIR/php_errors.log";
    }
    
    location ~ /\.ht {
        deny all;
    }
}
EOF
    
    
    nginx -t || {
        echo "❌ Nginx配置错误" >&2
        exit 1
    }
    
    
    systemctl restart nginx php-fpm
    systemctl enable nginx php-fpm
}


show_summary() {
    echo -e "\n🎉 部署成功！"
    echo "========================================"
    echo "🌍 访问地址: http://您的服务器地址"
    echo "----------------------------------------"
    echo "========================================"
}


main() {
    generate_credentials
    create_directories
    install_dependencies
    setup_database
    deploy_application
    configure_webserver
    show_summary
}

main
